package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.TimeUnit;

/**
 * 切面：通知+切入点
 *
 * @author: atguigu
 * @create: 2025-03-11 10:09
 */
@Slf4j
@Aspect
@Component
public class GuiGuLoginAspect {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 认证状态校验环绕通知
     * 1.对所有控制层且使用@GuiGuLogin注解方法进行增强
     *
     * @param pjp        目标方法对象
     * @param guiGuLogin 注解对象，作用在目标方法上注解对象
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, GuiGuLogin guiGuLogin) throws Throwable {
        //一、前置逻辑
        //1.获取请求对象
        //1.1 通过请求上下文对象获取RequestAttributes(接口)
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //1.2 将接口转为实现类ServletRequestAttributes（实现类）
        ServletRequestAttributes rsa = (ServletRequestAttributes) requestAttributes;
        //1.3 获取请求对象
        HttpServletRequest request = rsa.getRequest();
        //2.从请求对象中获取请求头中的token  业界约定俗成授权头：Authorization
        String token = request.getHeader("token");

        //3.查询Redis中用户信息
        //3.1 构建当时登录存入Redis用户信息Key 形式：前缀+令牌
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        //3.2 查询Redis中用户基本信息
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);

        //4.如果用户信息为空且目标方法需登录方可访问。则抛出异常，响应业务状态码：208
        if(userInfoVo==null && guiGuLogin.required()){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        //5.如果用户存在说明是在登录状态，将用户ID存入ThreadLocal
        if(userInfoVo!=null){
            //5.1 判断key存活时间，如果小于规定阈值：6小时，则刷新key存活时间
            Long expireHours = redisTemplate.getExpire(loginKey, TimeUnit.HOURS);
            if(expireHours<=6){
                redisTemplate.expire(loginKey, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
            }
            AuthContextHolder.setUserId(userInfoVo.getId());
        }

        //二、目标方法执行
        //6.执行JavaEE三层逻辑
        Object retVal = pjp.proceed();

        //三、后置逻辑
        //7.清理ThreadLocal 避免出现内存泄漏 造成OOM
        AuthContextHolder.removeUserId();
        return retVal;
    }


}
